<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-us" lang="en-us">
<head>
  <link href="https://gmpg.org/xfn/11" rel="profile">
  <meta http-equiv="content-type" content="text/html; charset=utf-8">
  <meta name="generator" content="Hugo 0.68.3" />

  
  <meta name="viewport" content="width=device-width, initial-scale=1.0">

  <title>python基础装饰器 &middot; 我的博客</title>
  <meta name="description" content="" />

  
  <link type="text/css" rel="stylesheet" href="/my_technology_blog/css/print.css" media="print">
  <link type="text/css" rel="stylesheet" href="/my_technology_blog/css/poole.css">
  <link type="text/css" rel="stylesheet" href="/my_technology_blog/css/syntax.css">
  <link type="text/css" rel="stylesheet" href="/my_technology_blog/css/hyde.css">
    <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Abril+Fatface|PT+Sans:400,400i,700">


  
  <link rel="apple-touch-icon-precomposed" sizes="144x144" href="/apple-touch-icon-144-precomposed.png">
  <link rel="shortcut icon" href="/favicon.png">

  
  
</head>

  <body class="theme-base-09 ">
  <aside class="sidebar">
  <div class="container sidebar-sticky">
    <div class="sidebar-about">
      <a href="/my_technology_blog/"><h1>我的博客</h1></a>
      <p class="lead">
       这里是任永刚的个人博客 
      </p>
    </div>

    <nav>
      <ul class="sidebar-nav">
        <li><a href="/my_technology_blog/">Home</a> </li>
        
      </ul>
    </nav>

    <p>&copy; 2020. All rights reserved. </p>
  </div>
</aside>

    <main class="content container">
    <div class="post">
  <h1>python基础装饰器</h1>
  <time datetime=2020-04-26T00:00:00Z class="post-date">Sun, Apr 26, 2020</time>
  <h1 id="装饰器">装饰器</h1>
<h2 id="1-装饰器定义">1. 装饰器定义</h2>
<pre><code>不能修改被装饰函数的源代码，不能修改被装饰函数的调用方式，为其他函数添加其他功能
</code></pre>
<h2 id="2-使用高阶函数模拟装饰器">2. 使用高阶函数模拟装饰器</h2>
<pre><code>#! /usr/bin/env python
# -*- coding: utf-8 -*-
import time
def timer(func):
    start_time = time.time()
    func()
    print '函数执行时间为', time.time() - start_time
def test():
    print '开始执行test'
    time.sleep(3)
    print 'test执行结束'
timer(test)
'''
开始执行test
test执行结束
函数执行时间为 3.00332999229
'''
</code></pre>
<h2 id="3-计算运行时间装饰器">3. 计算运行时间装饰器</h2>
<pre><code>import time
def timer(func):   #timer(test1)  func=test1
    def deco(*args,**kwargs):
        start_time = time.time()
        func(*args,**kwargs)      #run test1
        stop_time = time.time()
        print(&quot;running time is %s&quot;%(stop_time-start_time))
    return deco
@timer     # test1=timer(test1)
def test1():
    time.sleep(3)
    print(&quot;in the test1&quot;)
test1()
</code></pre>
<h2 id="4-装饰器使用场景">4. 装饰器使用场景</h2>
<pre><code>授权：装饰器能有助于检查某个人是否被授权去使用一个web应用的端点(endpoint)。它们被大量使用于Flask和Django web框架中
日志：在记录日志的地方添加装饰器
缓存：通过装饰器获取缓存中的值
</code></pre>

</div>


    </main>

    
      
    
  </body>
</html>
